package com.iqiyi.pps.epg.core.rpc.ticket;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.iqiyi.pps.epg.api.model.web.query.TFilter;
import com.iqiyi.pps.epg.api.model.web.query.TPage;
import com.iqiyi.pps.epg.api.model.web.query.TResponse;
import com.iqiyi.pps.epg.api.model.web.ticket.*;
import com.iqiyi.pps.epg.api.server.web.ticket.TicketWebService;
import com.iqiyi.pps.epg.core.model.ticket.TicketData;
import com.iqiyi.pps.epg.core.model.ticket.TicketLiveCheck;
import com.iqiyi.pps.epg.core.model.ticket.TicketLog;
import com.iqiyi.pps.epg.core.model.ticket.TicketStatus;
import com.iqiyi.pps.epg.core.service.ticket.ITicketService;
import com.iqiyi.pps.epg.core.utils.Constants;
import com.iqiyi.pps.epg.core.utils.WriteSystemLogUtil;
import org.apache.thrift.TException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.sql.Timestamp;
import java.util.List;

/**
 * Created by karkarrotxu on 2017/8/16.
 */
public class TicketWebServiceImpl implements TicketWebService.Iface {
    public static Logger logger = LoggerFactory.getLogger(TicketWebServiceImpl.class);
    public static final String DB_ERROR = "数据库异常";

    private ITicketService getTicketService() {
        return WriteSystemLogUtil.getInstance().getTicketService();
    }

    @Override
    public long saveLog(TTicketLog entity) throws TException {
        if (entity != null) {
            TicketLog logEntity = new TicketLog();
            logEntity.setDataId(entity.getDataId());
            logEntity.setType(entity.getType());
            logEntity.setDescr(entity.getDescr());
            logEntity.setUser(entity.getUser());
            logEntity.setAddTime(new Timestamp(System.currentTimeMillis()));
            try {
                getTicketService().saveLog(logEntity);
            } catch (Exception e) {
                logger.error("saveLog", e);
            }
            return logEntity.getId();
        }
        return -1;
    }

    @Override
    public TTicketLogPage searchLog(TPage page, TFilter filter) throws TException {
        ITicketService service = getTicketService();
        return service.findLogPage(page, filter);
    }

    @Override
    public TResponse addTicketData(TTicketData entity) throws TException {
        TResponse tResponse = new TResponse();
        tResponse.setCode(Constants.CODE_ERROR);
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("retValue", 0);
        if (entity != null) {
            try {
                TFilter filter = new TFilter();
                filter.putToFilters("EQI_dataType", entity.getDataType() + "");
                filter.putToFilters("EQL_resourceId", entity.getResourceId() + "");
                List<TicketData> list = getTicketService().findTicketDataList(filter);
                if (list.size() == 0) {
                    TicketData dataEntity = new TicketData();
                    dataEntity.setTitle(entity.getTitle());
                    dataEntity.setExecutor(entity.getExecutor());
                    dataEntity.setDataType(entity.getDataType());
                    dataEntity.setPriority(entity.getPriority());
                    dataEntity.setDetail(entity.getDetail());
                    dataEntity.setStatus(entity.getStatus());
                    dataEntity.setReporter(entity.getReporter());
                    dataEntity.setResourceId(entity.getResourceId());
                    dataEntity.setDeadline(entity.getDeadline());
                    dataEntity.setOaDocUrl(entity.getOaDocUrl());
                    dataEntity.setOaDocNo(entity.getOaDocNo());
                    dataEntity.setOaDocEditorStatus(entity.getOaDocEditorStatus());
                    dataEntity.setAddTime(new Timestamp(System.currentTimeMillis()));
                    long regId = getTicketService().addTicketData(dataEntity);
                    tResponse.setCode(Constants.CODE_SUC);
                    jsonObject.put("retValue", regId);
                    tResponse.setJsonData(jsonObject.toJSONString());
                //    getTicketService().saveLog(builderNewLog(dataEntity));
                } else {
                    TicketData ticketData = list.get(0);
                    ticketData.setExecutor(entity.getExecutor());
                    ticketData.setPriority(entity.getPriority());
                    ticketData.setDetail(entity.getDetail());
                    ticketData.setStatus(entity.getStatus());
                    ticketData.setDeadline(entity.getDeadline());
                    getTicketService().editTicketData(ticketData);
                    tResponse.setCode(Constants.CODE_SUC);
                    jsonObject.put("retValue", ticketData.getId());
                    tResponse.setJsonData(jsonObject.toJSONString());
                }
            } catch (Exception e) {
                tResponse.setJsonData(jsonObject.toJSONString());
                logger.error("saveLog", e);
            }
        }
        return tResponse;
    }

    @Override
    public TResponse cancelTicketData(TTicketData entity) throws TException {
        TResponse tResponse = new TResponse();
        tResponse.setCode(Constants.CODE_ERROR);
        if (entity != null) {
            try {
                TFilter filter = new TFilter();
                filter.putToFilters("EQI_dataType", entity.getDataType() + "");
                filter.putToFilters("EQL_resourceId", entity.getResourceId() + "");
                List<TicketData> list = getTicketService().findTicketDataList(filter);
                if (list.size() == 0) {
                    tResponse.setMsg("No data");
                } else {
                    TicketData ticketData = list.get(0);
                    ticketData.setStatus(entity.getStatus());
                    getTicketService().editTicketData(ticketData);
                    tResponse.setCode(Constants.CODE_SUC);
                }
            } catch (Exception e) {
                tResponse.setCode(Constants.CODE_FAIL);
                tResponse.setMsg(DB_ERROR);
                logger.error("saveLog", e);
            }
        }
        return tResponse;
    }


    @Override
    public TResponse editTicketData(TTicketData entity) throws TException {
        TResponse tResponse = new TResponse();
        try {
            ITicketService service = getTicketService();
            TicketData ticketData = getTicketService().findTicketDataId(entity.getId());
            if (ticketData == null) {
                tResponse.setCode(Constants.CODE_FAIL);
                tResponse.setMsg("no data");
                return tResponse;
            }
        //    getTicketService().saveLog(builderEditLog(ticketData, entity));
            ticketData.setExecutor(entity.getExecutor());
            ticketData.setPriority(entity.getPriority());
            ticketData.setDetail(entity.getDetail());
            ticketData.setStatus(entity.getStatus());
            ticketData.setDeadline(entity.getDeadline());
            if (TicketStatus.DEAL.getStatusIndex() == ticketData.getStatus()) {
                ticketData.setCompleteTime(new Timestamp(System.currentTimeMillis()));
            }
            service.editTicketData(ticketData);
            tResponse.setCode(Constants.CODE_SUC);
        } catch (Exception e) {
            logger.error("editTicketData", e);
            tResponse.setCode(Constants.CODE_FAIL);
            tResponse.setMsg(DB_ERROR);
        }
        return tResponse;
    }

    @Override
    public TResponse assignTicketData(long id, String executor) throws TException {
        TResponse tResponse = new TResponse();
        try {
            ITicketService service = getTicketService();
            TicketData ticketData = getTicketService().findTicketDataId(id);
            if (ticketData == null) {
                tResponse.setCode(Constants.CODE_FAIL);
                tResponse.setMsg("no data");
                return tResponse;
            }
            ticketData.setExecutor(executor);
            service.editTicketData(ticketData);
            tResponse.setCode(Constants.CODE_SUC);
        } catch (Exception e) {
            logger.error("assignTicketData", e);
            tResponse.setCode(Constants.CODE_FAIL);
            tResponse.setMsg(DB_ERROR);
        }
        return tResponse;
    }

    @Override
    public TResponse delTicketData(TFilter filter) throws TException {
        return null;
    }

    @Override
    public TTicketDataPage searchTicketData(TPage page, TFilter filter) throws TException {
        ITicketService service = getTicketService();
        return service.findTicketDataPage(page, filter);
    }

    @Override
    public TResponse addTicketHistory(TTicketHistory entity) throws TException {
        TResponse tResponse = new TResponse();
        tResponse.setCode(Constants.CODE_ERROR);
        return tResponse;
    }

    @Override
    public TTicketHistoryPage searchTicketHistory(TPage page, TFilter filter) throws TException {
        return null;
    }

    public TResponse getTicketLiveCheck(long dataId) throws TException {
        TResponse tResponse = new TResponse();
        tResponse.setCode(Constants.CODE_ERROR);
        try{
            ITicketService service = getTicketService();
            JSONObject jsonObject = new JSONObject();
            TicketLiveCheck data =  service.findTicketLiveCheckByDataId( dataId);
            jsonObject.put("isNew",data == null);
            jsonObject.put("data", JSON.toJSON(data));
            tResponse.setCode(Constants.CODE_SUC);
            tResponse.setJsonData(jsonObject.toJSONString());
        }catch (Exception e){
            logger.error("getTicketLiveCheck",e);
        }
        return tResponse;
    }

    public TResponse submitTicketLiveCheck(TTicketLiveCheck entity) throws TException {
        TResponse tResponse = new TResponse();
        tResponse.setCode(Constants.CODE_ERROR);
        try{
            ITicketService service = getTicketService();
            JSONObject jsonObject = new JSONObject();
            TicketLiveCheck data =  service.findTicketLiveCheckByDataId( entity.getDataId());
            if(data == null){
                data = new TicketLiveCheck();
                data.setOpUser(entity.getUser());
                data.setType(entity.getType());
                data.setDataId(entity.getDataId() );
                data.setAddTime(new Timestamp(System.currentTimeMillis()));
            }
            data.setDetail(entity.getDetail());
            service.updateLiveCheck(data);
            tResponse.setJsonData(jsonObject.toJSONString());
            tResponse.setCode(Constants.CODE_SUC);
        }catch (Exception e){
            logger.error("getTicketLiveCheck",e);
        }
        return tResponse;
    }

    @Override
    public List<TTicketSysConfig> filterConfigs(TFilter filter) throws TException {
        ITicketService service = getTicketService();
        return service.filterConfigs( filter);
    }

    @Override
    public List<TTicketSysConfig> getAllConfigs() throws TException {
        ITicketService service = getTicketService();
        return service.getAllConfigs();
    }
}
